package org.xxpay.pay.channel.zy2pay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.*;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;
import org.xxpay.pay.util.MyHttp;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class Zy2payPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(Zy2payPaymentService.class);

    @Override
    public String getChannelName() {
        return Zy2payConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        return doPay(payOrder);
    }

    /**
     *
     * @param payOrder
     * @return
     */
    public AbstractRes doPay(PayOrder payOrder) {
        Zy2payConfig zy2payConfig = new Zy2payConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        // 订单参数
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("pay_memberid", zy2payConfig.getMemberId());   //商户号
        paramsMap.put("pay_orderid", payOrder.getPayOrderId());   //订单号
        paramsMap.put("pay_applydate", DateUtil.date2Str(new Date()));  //提交时间 时间格式：2016-12-26 18:18:18
        paramsMap.put("pay_bankcode", zy2payConfig.getPayType());   //银行编码
        paramsMap.put("pay_notifyurl", super.getNotifyUrl(getChannelName(), dbConfig));   //服务端通知
        paramsMap.put("pay_callbackurl", super.getNotifyUrl(getChannelName(), dbConfig) + "?payOrderId=" + payOrder.getPayOrderId()); //页面跳转通知
        paramsMap.put("pay_amount", AmountUtil.convertCent2Dollar(payOrder.getAmount()+""));    //订单金额

        try {
            // 订单签名
            paramsMap.put("pay_md5sign", PayDigestUtil.getSign(paramsMap, zy2payConfig.getApiKey()));    //签名
            paramsMap.put("pay_productname", payOrder.getSubject()); //商品名称 必填 & 不参与签名

            String toPayUrl = zy2payConfig.getReqUrlHost() + "/Pay_Index.html"; //请求网关地址
            _log.info("{}请求路径:{},请求数据:{}", getChannelName(), toPayUrl, paramsMap);
            String postResult = MyHttp.doPost(toPayUrl, paramsMap);
            _log.info("{},请求结果:{}", getChannelName(), postResult);
            if(StringUtils.isEmpty(postResult)) {
                return ApiBuilder.bizError("调起通道失败[没有返回数据]");
            }
            JSONObject jsonResult = JsonUtil.getJSONObjectFromJson(postResult);
            if(jsonResult == null) {
                return ApiBuilder.bizError("调起通道失败[没有返回数据]");
            }
            String code = jsonResult.getString("code");
            if("0".equals(code)) {
                JSONObject data = jsonResult.getJSONObject("data");// 支付URL
                String qrcode = data.getString("qrcode");
                StringBuffer payForm = new StringBuffer();
                payForm.append("<script>window.location.href = '"+qrcode+"';</script>");
                retObj.setPayMethod(PayConstant.PAY_METHOD_FORM_JUMP);
                retObj.setJumpInfo(payForm.toString(), qrcode);
                int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
                _log.info("[{}]更新订单状态为支付中:payOrderId={},payUrl={},payType={},result={}", getChannelName(), payOrder.getPayOrderId(), toPayUrl, zy2payConfig.getPayType(), updateCount);
                return retObj;
            }else {
                String msg = jsonResult.getString("msg");
                return ApiBuilder.bizError("调起通道失败[通道提示：" + msg +"]");
            }
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("调起通道异常");
        }
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        String logPrefix = "【" + getChannelName() + "支付订单查询】";
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询,payOrderId={}", logPrefix, payOrderId);
        return QueryRetMsg.waiting();
    }

}
